#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
提示词生成器主程序

提供完整的提示词生成服务，整合所有组件。
"""

import sys
import os
import json
import logging
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from src.text.prompt_generator import prompt_generator

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("prompt_generator.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("prompt_generator_main")


def load_visual_analysis(input_file=None):
    """
    加载视觉分析结果
    
    Args:
        input_file: 输入文件路径
        
    Returns:
        dict: 视觉分析结果
    """
    if input_file and os.path.exists(input_file):
        try:
            with open(input_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            logger.error(f"加载输入文件失败: {str(e)}")
            raise
    
    # 如果没有输入文件，返回示例数据
    return {
        "video_id": "example_video_001",
        "scene_setting": "校园操场",
        "theme_type": "体育活动",
        "objects": ["学生", "足球", "篮球架", "跑道"],
        "activities": ["踢足球", "打篮球", "跑步"],
        "atmosphere": "活力四射"
    }


def generate_prompts_for_video(visual_analysis):
    """
    为视频生成提示词
    
    Args:
        visual_analysis: 视觉分析结果
        
    Returns:
        dict: 生成的提示词
    """
    # 获取提示词生成器实例
    generator = prompt_generator.get_prompt_generator()
    
    # 生成所有类目提示词
    all_prompts = generator.generate_all_prompts(visual_analysis)
    
    # 生成缺失类目提示词
    missing_prompts = generator.generate_missing_prompts(visual_analysis)
    
    # 整合结果
    result = {
        "video_id": visual_analysis.get("video_id", "unknown"),
        "timestamp": datetime.now().isoformat(),
        "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "all_prompts": all_prompts,
        "missing_prompts": missing_prompts,
        "summary": {
            "total_categories": len(all_prompts),
            "missing_categories": len(missing_prompts)
        }
    }
    
    return result


def save_results(results, output_file=None):
    """
    保存结果到文件
    
    Args:
        results: 生成的结果
        output_file: 输出文件路径
    """
    if not output_file:
        # 如果没有指定输出文件，生成默认文件名
        video_id = results.get("video_id", "unknown")
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_file = f"prompts_{video_id}_{timestamp}.json"
    
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(results, f, ensure_ascii=False, indent=2)
        logger.info(f"结果已保存到: {output_file}")
        return output_file
    except Exception as e:
        logger.error(f"保存结果失败: {str(e)}")
        raise


def print_results_summary(results):
    """
    打印结果摘要
    
    Args:
        results: 生成的结果
    """
    print("\n===== 提示词生成结果摘要 =====")
    print(f"视频ID: {results.get('video_id', 'unknown')}")
    print(f"生成时间: {results.get('generated_at', '')}")
    print(f"总类目数: {results['summary']['total_categories']}")
    print(f"缺失类目数: {results['summary']['missing_categories']}")
    
    print("\n已生成的提示词:")
    for category, prompt in results['all_prompts'].items():
        print(f"- {category}: {prompt[:50]}..." if len(prompt) > 50 else f"- {category}: {prompt}")
    
    if results['missing_prompts']:
        print("\n缺失类目提示词:")
        for category, prompt in results['missing_prompts'].items():
            print(f"- {category}: {prompt[:50]}..." if len(prompt) > 50 else f"- {category}: {prompt}")
    
    print("\n==============================\n")


def main():
    """
    主函数
    """
    logger.info("提示词生成器服务启动")
    
    # 解析命令行参数
    input_file = None
    output_file = None
    
    if len(sys.argv) > 1:
        input_file = sys.argv[1]
    if len(sys.argv) > 2:
        output_file = sys.argv[2]
    
    try:
        # 加载视觉分析结果
        logger.info(f"加载视觉分析结果，输入文件: {input_file}")
        visual_analysis = load_visual_analysis(input_file)
        logger.debug(f"视觉分析结果: {visual_analysis}")
        
        # 生成提示词
        logger.info("开始生成提示词")
        results = generate_prompts_for_video(visual_analysis)
        logger.info("提示词生成完成")
        
        # 保存结果
        saved_file = save_results(results, output_file)
        
        # 打印结果摘要
        print_results_summary(results)
        
        logger.info(f"提示词生成服务完成，结果已保存到: {saved_file}")
        return 0
        
    except Exception as e:
        logger.error(f"提示词生成服务失败: {str(e)}")
        print(f"错误: {str(e)}")
        return 1


if __name__ == "__main__":
    sys.exit(main())